package com.zhentao.controller;

import com.zhentao.service.MinioService;
import io.minio.MinioClient;
import io.minio.Result;
import io.minio.messages.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/images")
@CrossOrigin(origins = "*") // 允许跨域请求
public class ImageController {
    @Autowired
    private MinioService minioService;
    
    @Autowired
    private MinioClient minioClient;
    
    @Value("${minio.bucketName}")
    private String bucketName;

    @PostMapping("/upload")
    public ResponseEntity<?> uploadImage(@RequestParam("image") MultipartFile file) {
        try {
            String imageUrl = minioService.uploadImage(file);
            System.out.println("图片上传成功，访问URL: " + imageUrl);
            return ResponseEntity.ok().body("{\"url\":\"" + imageUrl + "\"}");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body("图片上传失败: " + e.getMessage());
        }
    }

    @GetMapping("/list")
    public ResponseEntity<?> listImages() {
        try {
            List<String> imageUrls = new ArrayList<>();
            Iterable<Result<Item>> results = minioClient.listObjects(
                    io.minio.ListObjectsArgs.builder()
                            .bucket(bucketName)
                            .build());

            for (Result<Item> result : results) {
                Item item = result.get();
                String imageUrl = minioClient.getObjectUrl(bucketName, item.objectName());
                imageUrls.add(imageUrl);
            }

            return ResponseEntity.ok().body(imageUrls);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body("获取图片列表失败: " + e.getMessage());
        }
    }
}
